package com.lwbpro.web.controller.system;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.EasyExcel;
import com.lwbpro.system.domain.vo.ExamManageExcelVO;
import com.lwbpro.system.domain.vo.ExamManageReqVO;
import com.lwbpro.system.domain.vo.ExcelImportListener;
import com.lwbpro.system.excel.ExcelUtils;
import com.lwbpro.system.excel.LocalDateConverter;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.lwbpro.common.annotation.Log;
import com.lwbpro.common.core.controller.BaseController;
import com.lwbpro.common.core.domain.AjaxResult;
import com.lwbpro.common.enums.BusinessType;
import com.lwbpro.system.domain.ExamManage;
import com.lwbpro.system.service.IExamManageService;
import com.lwbpro.common.utils.poi.ExcelUtil;
import com.lwbpro.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 考试管理Controller
 *
 * @author achievement
 * @date 2024-08-28
 */
@RestController
@RequestMapping("/system/manage")
public class ExamManageController extends BaseController {
    @Autowired
    private IExamManageService examManageService;

    /**
     * 查询考试管理列表
     */
    @PreAuthorize("@ss.hasPermi('system:manage:list')")
    @GetMapping("/list")
    public TableDataInfo list(ExamManageReqVO reqVO) {
        startPage();
        List<ExamManage> list = examManageService.selectExamManageList(reqVO);
        return getDataTable(list);
    }

    /**
     * 导出考试管理列表
     */
    @PreAuthorize("@ss.hasPermi('system:manage:export')")
    @Log(title = "考试管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ExamManageReqVO reqVO) {
        List<ExamManage> list = examManageService.selectExamManageList(reqVO);
        ExcelUtil<ExamManage> util = new ExcelUtil<ExamManage>(ExamManage.class);
        util.exportExcel(response, list, "考试管理数据");
    }

    /**
     * 获取考试管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:manage:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(examManageService.selectExamManageById(id));
    }

    @PreAuthorize("@ss.hasPermi('system:manage:query')")
    @GetMapping(value = "/examId/{id}")
    public AjaxResult barGraph(@PathVariable Long id) {
        return success(examManageService.barGraph(id));
    }

    /**
     * 新增考试管理
     */
    @PreAuthorize("@ss.hasPermi('system:manage:add')")
    @Log(title = "考试管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ExamManage examManage) {
        return toAjax(examManageService.insertExamManage(examManage));
    }

    /**
     * 修改考试管理
     */
    @PreAuthorize("@ss.hasPermi('system:manage:edit')")
    @Log(title = "考试管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ExamManage examManage) {
        return toAjax(examManageService.updateExamManage(examManage));
    }

    /**
     * 删除考试管理
     */
    @PreAuthorize("@ss.hasPermi('system:manage:remove')")
    @Log(title = "考试管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(examManageService.deleteExamManageByIds(ids));
    }

    @PostMapping("/importTemplate")
    @PreAuthorize("@ss.hasPermi('system:manage:importTemplate')")
    public void importTemplate(HttpServletResponse response) throws IOException {
        //模版路径
        InputStream resourceAsStream = ExcelUtils.class.getClassLoader().getResourceAsStream("excel-template/exam_manage.xlsx");

        // 设置 header 和 contentType。写在最后的原因是，避免报错时，响应 contentType 已经被修改了
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("考试管理导入模版.xlsx", "UTF-8"));
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");

        EasyExcel.write(response.getOutputStream()).withTemplate(resourceAsStream).sheet().doFill(CollUtil.newHashMap());
    }

    @Log(title = "考试管理导入", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:manage:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        List<ExamManageExcelVO> examManageList = EasyExcel.read(file.getInputStream(), ExamManageExcelVO.class, new ExcelImportListener())
                .autoCloseStream(true)  // 不要自动关闭，交给 Servlet 自己处理
                .registerConverter(new LocalDateConverter())
                .headRowNumber(3)// 跳过表头
                .doReadAllSync();
        String operName = getUsername();
        return success(examManageService.importCase(examManageList, updateSupport, operName, file.getOriginalFilename()));
    }
}
